<template>
  <view class="container pb-ios">
    <u-navbar
      :background="{ backgroundColor: '#fff' }"
      backIconColor="#333"
      title-color="#333"
      title="付款给商家"
      :border-bottom="false"
      :is-back="false"
    >
      <view style="padding: 0 20rpx" @click="$utils.goToUserCenter()">
        <u-icon name="close" size="30"></u-icon>
      </view>
      <!-- #ifndef MP -->
      <view
        v-if="userInfo"
        slot="right"
        class="dis-flex flex-x-center flex-y-center"
        style="padding: 0 20rpx"
        @click="$utils.route('/dine/scan/order')"
      >
        <u-icon name="/static/ddlb.png" size="30"></u-icon>
      </view>
      <!-- #endif -->
      <!-- #ifdef MP -->
      <view
        v-if="userInfo"
        class="dis-flex flex-x-center flex-y-center"
        style="padding: 0 10rpx"
        @click="$utils.route('/dine/scan/order')"
      >
        <text style="font-size: 30rpx">我的订单</text>
      </view>
      <!-- #endif -->
    </u-navbar>
    <view class="card store-box dis-flex" v-if="shopInfo">
      <u-image
        :src="shopInfo.logo"
        height="150rpx"
        width="150rpx"
        border-radius="10"
        mode="aspectFit"
      ></u-image>
      <view class="store-name dis-flex">
        <text>{{ shopInfo.name }}</text>
        <text class="category">{{ shopInfo.categoryName }}</text>
      </view>
      <view class="toshop" @click="toShop">去店铺</view>
    </view>
    <view class="card pay-input dis-flex flex-y-center">
      <text>¥</text>
      <input
        v-model="num"
        type="digit"
        placeholder="请输入付款金额"
        @click="open"
        :readonly="true"
        :focus="false"
        class="flex-1"
      />
      <!--  坑：此处不使用 u-button 的话，使用 text、button、view 等 @click 不生效，原因未知   -->
      <u-button v-if="num" type="primary" size="mini" plain :hair-line="false" @click="onClear">
        清除
      </u-button>
    </view>
    <view
      v-if="canGrantRedPacket"
      style="
        margin-left: 20rpx;
        margin-right: 20rpx;
        margin-top: 50rpx;
        padding: 20rpx;
        background: #eee;
        border-radius: 10rpx;
        color: #666;
        font-size: 24rpx;
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
      "
    >
      <u-parse :html="redPacketGrantTips"></u-parse>
      <view class="rule_btn">
        <!--  坑：此处不使用 u-button 的话，使用 text、button、view 等 @click 不生效，原因未知   -->
        <u-button type="primary" size="mini" :hair-line="false" plain @click="showRuleModel = true">
          <view class="dis-flex flex-x-center flex-y-end">
            <text style="margin-right: 10rpx">红包规则</text>
            <u-icon name="/static/tishi-b.png" size="28"></u-icon>
          </view>
        </u-button>
      </view>
    </view>
    <!-- #ifdef MP-WEIXIN -->
    <button
      v-if="!newCustomer.login"
      class="login_btn"
      open-type="getPhoneNumber"
      @getphonenumber="wxLogin"
    >
      <text>立即登录</text>
      <text style="font-size: 28rpx; margin-left: 10rpx">领券领红包享优惠</text>
    </button>
    <!-- #endif -->
    <!-- #ifndef MP-WEIXIN -->
    <button v-if="!newCustomer.login" class="login_btn" @click="toLogin()">
      <text>去登录</text>
      <text style="font-size: 28rpx; margin-left: 10rpx">领券领红包享优惠</text>
    </button>
    <!-- #endif -->
    <jia-PayKeyboard
      ref="keyWord"
      v-model="num"
      :confirmStyle="confirmStyle"
      confirmText="付款"
      :overlayClose="false"
      @input="inp"
      @confirm="confirm"
      @hide="hide"
    >
    </jia-PayKeyboard>

    <u-popup
      v-model="showNewCustomerPopup"
      mode="bottom"
      width="550"
      height="auto"
      :closeable="true"
      :mask-close-able="false"
      border-radius="15"
    >
      <text
        v-if="!newCustomer.login"
        style="margin: 30rpx; display: flex; align-items: baseline; justify-content: left"
      >
        未登录，需原价支付，登录后享更多优惠
      </text>
      <text
        v-else
        style="margin: 30rpx; display: flex; align-items: baseline; justify-content: left"
      >
        {{ newCustomer.matched ? '新顾客，享首单优惠' : '已享受过首单优惠，需原价支付' }}
      </text>
      <view
        style="
          margin-left: 20rpx;
          margin-right: 20rpx;
          margin-top: 50rpx;
          display: flex;
          align-items: baseline;
          justify-content: center;
        "
      >
        <text>原价</text>
        <text style="color: orange">¥{{ (newCustomer.originPrice * 0.01).toFixed(2) }}</text>
        <text>，首单优惠价</text>
        <text style="color: orange">¥{{ (newCustomer.price * 0.01).toFixed(2) }}</text>
      </view>
      <view
        v-if="newCustomer.rewardType === 1 && canGrantRedPacket"
        style="
          margin-left: 20rpx;
          margin-right: 20rpx;
          margin-top: 10rpx;
          padding: 20rpx;
          background: #eee;
          border-radius: 10rpx;
          color: #666;
          font-size: 24rpx;
          display: flex;
          align-items: flex-start;
          justify-content: space-between;
        "
      >
        <u-parse :html="redPacketGrantTips"></u-parse>
        <view class="rule_btn">
          <u-button
            type="primary"
            size="mini"
            :hair-line="false"
            plain
            @click="showRuleModel = true"
          >
            <view class="dis-flex flex-x-center flex-y-end">
              <text style="margin-right: 10rpx">红包规则</text>
              <u-icon name="/static/tishi-b.png" size="28"></u-icon>
            </view>
          </u-button>
        </view>
      </view>
      <view
        v-if="newCustomer.giftActivities"
        style="margin-top: 30rpx; margin-left: 20rpx; margin-right: 20rpx"
      >
        <u-line color="#C1C0C9"></u-line>
        <GiftActivity :items="newCustomer.giftActivities" :login="newCustomer.login"></GiftActivity>
      </view>
      <view
        v-if="!newCustomer.login"
        class="dis-flex flex-x-center flex-y-center"
        style="margin-bottom: 30rpx"
      >
        <text
          class="guide-btn origin-btn"
          :class="{ disable: disable }"
          @click="newCustomerPay(newCustomer.originPrice, newCustomer.originPrice)"
          >原价支付
        </text>
        <!-- #ifdef MP-WEIXIN -->
        <button
          v-if="!newCustomer.login"
          class="guide-btn"
          open-type="getPhoneNumber"
          @getphonenumber="wxLogin"
        >
          登录享优惠
        </button>
        <!-- #endif -->
        <!-- #ifndef MP-WEIXIN -->
        <text class="guide-btn" @click="toLogin()">登录享优惠</text>
        <!-- #endif -->
      </view>
      <view v-else class="dis-flex flex-x-center flex-y-center" style="margin-bottom: 30rpx">
        <text
          class="guide-btn"
          :class="{ disable: disable }"
          style="margin-bottom: 30rpx"
          @click="newCustomerPay(newCustomer.price, newCustomer.originPrice)"
        >
          {{ newCustomer.matched ? '新客价支付' : '原价支付' }}
        </text>
      </view>
    </u-popup>

    <u-popup
      v-model="promotionModel"
      mode="bottom"
      width="550"
      height="auto"
      :closeable="true"
      :mask-close-able="false"
      border-radius="15"
    >
      <view class="infoView" v-if="paySetting">
        <view class="totalView dis-flex" style="padding-bottom: 10rpx" @click="onPreAll(-1)">
          <view class="totalTitle">原价</view>
          <view class="flex-1"></view>
          <view class="dis-flex flex-x-center">
            <view class="mr-20">¥{{ (paySetting.originPrice * 0.01).toFixed(2) }}</view>
            <u-icon name="/static/selected.png" size="36rpx" v-if="PrePoints == -1"></u-icon>
            <u-icon v-else name="/static/unselect.png" size="36rpx"></u-icon>
          </view>
        </view>
        <view
          class="totalView dis-flex"
          v-if="paySetting.promotions && paySetting.promotions.length > 0"
          v-for="(promotion, index) in paySetting.promotions"
          :key="index"
          @click="onPreAll(index)"
        >
          <view class="totalTitle">{{ promotion.name }}</view>
          <view
            v-if="
              newCustomer.login &&
              (promotion.type === 7 ||
                promotion.type === 8 ||
                promotion.type === 20 ||
                promotion.type === 30)
            "
            style="color: #0f76bc; margin: 0 10rpx"
            @click.stop.prevent="onPointList(index)"
            >查看明细
          </view>
          <view class="flex-1"></view>
          <view class="dis-flex flex-x-center">
            <view class="point flex-1 mr-20" style="font-size: 28rpx">
              {{ promotion.note }}
            </view>
            <view class="can-select">
              <u-icon name="/static/selected.png" size="36rpx" v-if="PrePoints === index"></u-icon>
              <u-icon v-else name="/static/unselect.png" size="36rpx"></u-icon>
            </view>
          </view>
        </view>
        <u-line v-if="(!userInfo || !userInfo.isVip) && zekou < 10"></u-line>
        <view class="open-vip" v-if="(!userInfo || !userInfo.isVip) && zekou < 10" @click="toSvip">
          <view class="vip-tl dis-flex flex-y-center">
            <view
              class="bt dis-flex flex-y-center flex-x-center"
              style="width: 100rpx; margin-right: 10rpx"
            >
              <u-icon class="bt-icon" name="/static/vip.png" size="36rpx"></u-icon>
              <text>VIP</text>
            </view>
            <view class="des">
              <text>开通会员，本单立享</text>
              <text class="col bold">{{ zekou }}</text>
              <text class="col">折</text>
              <text>优惠</text>
            </view>
          </view>
          <view class="vip-qy" v-if="cards">
            会员费：充¥{{ (cards.deductPrice * 0.01).toFixed(0) }}送{{ cards.givePoint }}积分
          </view>
          <view class="description" v-if="cards">{{ cards.days }}天有效期 到期前可续费</view>
        </view>
        <view v-if="giftActivities" style="margin-top: 30rpx">
          <u-line color="#C1C0C9"></u-line>
          <GiftActivity :items="giftActivities" :login="newCustomer.login"></GiftActivity>
        </view>
        <view style="height: 200rpx"></view>
        <view class="fixed-wapper dis-flex">
          <view class="other dis-flex flex-y-between flex-y-center">
            <view class="count">¥{{ (payPrice * 0.01).toFixed(2) }}</view>
            <view v-if="Number(discountPrice) > 0" class="count" style="font-size: 28rpx"
              >优惠¥{{ (discountPrice * 0.01).toFixed(2) }}
            </view>
            <view @click="submit" :class="{ disable: disable }" class="submit-btn"> 立即支付</view>
          </view>
        </view>
      </view>
    </u-popup>

    <u-popup v-model="needLoginPopup" mode="center" width="500rpx" border-radius="10" height="auto">
      <view class="close-wapper">
        <view class="title">温馨提示</view>
        <view class="des" v-if="promotionType === 21">新用户首单享超低折扣，是否去授权登录？</view>
        <view class="des" v-else-if="promotionType === 30">授权登录后可以使用红包抵扣</view>
        <view class="des" v-else-if="promotionType === 9"
          >{{ !userInfo ? '授权登录后才能使用会员价' : '成为会员后才能使用会员价' }}
        </view>
        <view class="des" v-else-if="promotionType === 7">授权登录后才能使用优惠券抵扣</view>
        <view class="des" v-else-if="promotionType === 8">授权登录后才能使用积分抵扣</view>
        <view class="des" v-else-if="promotionType === 20">授权登录后才能使用收益豆抵扣</view>
        <view class="des" v-else>授权登录后才能使用该优惠</view>
        <view class="bt-group dis-flex">
          <!-- #ifdef MP-WEIXIN -->
          <button
            class="bt"
            v-if="isNewUser && !newCustomer.login"
            open-type="getPhoneNumber"
            @getphonenumber="wxLogin"
            >注册/登录
          </button>
          <button
            class="bt"
            v-else-if="!isNewUser && !newCustomer.login"
            open-type="getPhoneNumber"
            @getphonenumber="wxLogin"
            >登录
          </button>
          <!-- #endif -->
          <!-- #ifndef MP-WEIXIN -->
          <view class="bt" v-if="isNewUser && !newCustomer.login" @click="toLogin"
            >去注册/登录
          </view>
          <view class="bt" v-else-if="!isNewUser && !newCustomer.login" @click="toLogin"
            >去登录
          </view>
          <!-- #endif -->
          <view class="bt" v-else-if="userInfo && !userInfo.isVip" @click="toSvip">开通会员</view>
          <view class="bt bt-1" @click="giveUp">放弃优惠</view>
        </view>
      </view>
    </u-popup>

    <u-popup v-model="showRuleModel" mode="center" width="600" height="auto" border-radius="20">
      <view class="rule_box">
        <view class="tl"> 规则说明</view>
        <u-parse
          v-if="newCustomer && newCustomer.redPacketConfig"
          class="content"
          :html="newCustomer.redPacketConfig.note"
        ></u-parse>
        <view class="bt" @click="showRuleModel = false">知道了</view>
      </view>
    </u-popup>

    <u-popup
      v-model="showCouponPopup"
      mode="bottom"
      height="500"
      border-radius="15"
      :closeable="true"
      :mask-close-able="false"
    >
      <view class="coupon-popup">
        <view class="popup-header">
          <text class="title">选择优惠券</text>
        </view>
        <scroll-view
          v-if="availableCoupons && availableCoupons.length"
          style="max-height: 600rpx"
          :scroll-y="true"
        >
          <view
            class="coupon-item"
            v-for="(coupon, index) in availableCoupons"
            :key="index"
            @click="selectCoupon(coupon)"
          >
            <view class="coupon-info">
              <text class="coupon-name">{{ coupon.name }}</text>
              <text v-if="coupon.discountType === 1" class="coupon-desc"
                >满{{ (coupon.usePrice * 0.01).toFixed(2) }}元减{{
                  (coupon.discountPrice * 0.01).toFixed(2)
                }}元
              </text>
              <text v-else-if="coupon.discountType === 2" class="coupon-desc"
                >满{{ (coupon.usePrice * 0.01).toFixed(2) }}元打{{
                  (coupon.discountPercent * 0.1).toFixed(1)
                }}折，最多减免{{ (coupon.discountLimitPrice * 0.01).toFixed(2) }}元
              </text>
            </view>
            <u-icon
              v-if="form.couponId === coupon.id"
              name="/static/selected.png"
              size="36rpx"
            ></u-icon>
            <u-icon v-else name="/static/unselect.png" size="36rpx"></u-icon>
          </view>
        </scroll-view>
        <view v-else class="dis-flex flex-x-center flex-y-center" style="height: 200rpx"
          >暂无优惠券
        </view>
      </view>
    </u-popup>

    <PayPopup ref="payPopupRef" @close="closePay">
      <p style="font-size: 50rpx; font-weight: 600; padding: 20rpx; text-align: center">
        ¥{{ (payPrice * 0.01).toFixed(2) }}
      </p>
    </PayPopup>
  </view>
</template>

<script>
import PayPopup from '@/components/PayPopup.vue'
import GiftActivity from '@/components/gift_activity.vue'

export default {
  components: {
    PayPopup,
    GiftActivity
  },
  data() {
    return {
      from: '',
      num: '',
      confirmStyle: {
        backgroundColor: '#10A28F',
        fontSize: '48rpx !important'
      },
      showRuleModel: false,
      promotionModel: false,
      PrePoints: -1,
      promotionType: 0,
      PreType: 1,
      payMethod: '',
      payOrderId: 1,
      openid: '',
      shopInfo: null,
      inviteCode: null,
      paySetting: null,
      isNewUser: false,
      showNewCustomerPopup: false,
      newCustomer: {
        shopId: null,
        enabled: false,
        originPrice: 0,
        price: 0,
        rewardType: 0,
        redPacketAmount: 0,
        giftActivityIds: [],
        giftActivities: [],
        login: true,
        matched: false,
        redPacketConfig: {
          featureEnable: false,
          firstAmount: 0,
          continueMode: 0,
          continueAmount: 0,
          continueThresholdPrice: 0,
          continueGrantScene: 0,
          continueGrantStartTime: null,
          continueGrantEndTime: null,
          validationDays: 0,
          note: ''
        }
      },
      userInfo: null,
      form: {
        price: null,
        useVipPrice: false,
        useRedPacketDeduction: false,
        usePointDeduction: false,
        useCryptocurrencyDeduction: false,
        useCouponDeduction: false,
        couponId: null,
        shopId: null
      },
      isVip: false,
      needLoginPopup: false,
      openid: '',
      cards: null,
      payPrice: 0,
      discountPrice: 0,
      showCouponPopup: false,
      availableCoupons: [],
      redpacket: null,
      giftActivities: [],
      disable: false,
      zekou: 10
    }
  },
  mounted() {
    this.$refs.keyWord.open()
  },
  onLoad(options) {
    const app = this
    app.form.shopId = options.shopId || '1943511878332915714'
    app.from = options.from || ''
    app.$u
      .get('/app-api/shop/info/get', {
        id: app.form.shopId
      })
      .then((res) => {
        app.shopInfo = res.data
        app.inviteCode = res.data.inviteCode
      })
  },
  onShow() {
    const app = this
    app.userInfo = uni.getStorageSync('userInfo')
    console.debug('userInfo', app.userInfo)
    app.refreshData()
    if (!app.userInfo) {
      // 未登录的情况下视为新用户，保存商家的邀请码，注册登录后于商家绑定推广关系
      if (app.inviteCode) {
        console.debug('商家的邀请码：' + app.inviteCode)
        uni.setStorageSync('saleMemberNo', app.inviteCode)
      }
      app.silentLoginCheck()
    }
  },
  computed: {
    canGrantRedPacket() {
      if (!this.newCustomer) {
        return false
      }
      if (
        this.newCustomer.matched &&
        this.newCustomer.rewardType === 1 &&
        this.newCustomer.redPacketAmount > 0
      ) {
        return true
      }
      return this.newCustomer.redPacketConfig && this.newCustomer.redPacketConfig.featureEnable
    },
    redPacketGrantTips() {
      let tips = '<p>'
      if (!this.userInfo) {
        tips += '<span style="color:indianred;">登录</span>后，'
      }
      if (this.newCustomer.redPacketConfig.firstAmount > 0) {
        tips += '新客可获得'
        tips +=
          '<span style="color:orange;">' +
          (this.newCustomer.redPacketConfig.firstAmount * 0.01).toFixed(2) +
          '</span>'
        tips += '元商家专属红包。'
      }
      if (
        this.newCustomer.matched &&
        this.newCustomer.rewardType === 1 &&
        this.newCustomer.redPacketAmount > 0
      ) {
        tips += '首单支付后可获得'
        tips +=
          '<span style="color:orange;">' +
          (this.newCustomer.redPacketAmount * 0.01).toFixed(2) +
          '</span>'
        tips += '元商家专属红包。'
        tips += '</p>'
        return tips
      }
      if (this.newCustomer.redPacketConfig.continueMode === 1) {
        let timeRange = this.$utils.parseTime(
          this.newCustomer.redPacketConfig.continueGrantStartTime,
          '{h}:{i}'
        )
        timeRange += '-'
        timeRange += this.$utils.parseTime(
          this.newCustomer.redPacketConfig.continueGrantEndTime,
          '{h}:{i}'
        )
        tips += '在商家设定的时间段内（' + timeRange + '）'
      }
      tips += '<b>原价</b>满'
      tips +=
        '<span style="color:orange;">' +
        (this.newCustomer.redPacketConfig.continueThresholdPrice * 0.01).toFixed(2) +
        '</span>'
      tips += '元后'
      if (this.newCustomer.redPacketConfig.continueMode === 1) {
        tips += '支付多少就获得多少商家专属红包。'
      } else {
        tips += '支付可获得'
        tips +=
          '<span style="color:orange;">' +
          (this.newCustomer.redPacketConfig.continueAmount * 0.01).toFixed(2) +
          '</span>'
        tips += '元商家专属红包。'
      }
      tips += '</p>'
      return tips
    }
  },
  methods: {
    refreshData() {
      this.checkCustomer()
      this.checkVip()
    },
    checkCustomer() {
      const app = this
      app.$u
        .get('/app-api/trade/order/offline-scan/check-customer', {
          shopId: app.form.shopId
        })
        .then((res) => {
          if (res.code === 0) {
            app.newCustomer = res.data
            app.num = (app.newCustomer.originPrice * 0.01).toFixed(2)
            if (app.promotionModel) {
              app.needLoginPopup = !app.newCustomer.login
              app.confirm()
            }
            app.showNewCustomerPopup = app.newCustomer.enabled && app.from !== 'redpacket'
            if (app.newCustomer.login && !app.newCustomer.matched) {
              // 已登录的情况下若不享受首单优惠，则不展示首单优惠弹窗
              app.showNewCustomerPopup = false
            }
          }
        })
    },
    checkVip() {
      const app = this
      app.$u
        .get('/app-api/member/vip/my', {
          profile: false,
          cards: 1
        })
        .then((res) => {
          if (res.code === 0) {
            app.openid = res.data.openid
            if (app.openid) {
              uni.setStorageSync('wx_openid', app.openid)
            }
            app.cards = res.data.cards.length > 0 ? res.data.cards[0] : null
            if (app.userInfo) {
              app.userInfo.isVip = res.data.valid
            }
          }
        })
    },
    silentLoginCheck() {
      const app = this
      // #ifdef MP-WEIXIN
      uni.login({
        provider: 'weixin', //使用微信静默授权注册openid
        success: (loginRes) => {
          console.debug('weixin login: ' + JSON.stringify(loginRes))
          app.$u
            .get('/app-api/member/social-user/check-wxa-bind', {
              code: loginRes.code
            })
            .then((res) => {
              app.isNewUser = Boolean(res.data.bind) === false
              app.openid = res.data.openid
              if (app.openid) {
                uni.setStorageSync('wx_openid', app.openid)
              }
            })
        }
      })
      // #endif
      // #ifdef H5
      // 模拟新用户
      app.isNewUser = true
      // #endif
    },
    inp(e) {
      console.debug('输入', e)
    },
    confirm() {
      if (this.$u.test.isEmpty(this.num)) {
        this?.$u.toast('请输入付款金额')
        return
      }
      this.form.price = this.num * 100
      this.$u.post('/app-api/trade/order/offline-scan/preview', this.form).then((res) => {
        if (res.code !== 0) {
          this.$u.toast(res.msg)
          return
        }
        this.paySetting = res.data
        this.shopInfo = res.data.shop
        this.availableCoupons = res.data.coupons
        this.form.couponId = res.data.coupon?.id
        this.form.price = res.data.originPrice
        this.redpacket = res.data.redpacket
        this.inviteCode = res.data.inviteCode
        this.payPrice = res.data.payPrice
        this.discountPrice = res.data.discountPrice
        this.promotionModel = true
        this.giftActivities = res.data.giftActivities
        let vipIndex = res.data.promotions.findIndex(
          (item) => item.type === 9 // 会员价
        )
        if (vipIndex > -1) {
          let zekou =
            (res.data.originPrice - res.data.promotions[vipIndex].price) / res.data.originPrice
          this.zekou = (zekou * 10).toFixed(1)
        }
      })
    },
    open() {
      console.debug('打开数字键盘')
      this.$refs.keyWord.open()
    },
    onClear() {
      console.debug('清空输入')
      this.$refs.keyWord.clear()
    },
    hide() {
      console.debug('关闭数字键盘')
    },
    onPreAll(index) {
      if (index === -1) {
        // 原价
        this.PrePoints = index
        this.form.useRedPacketDeduction = false
        this.form.usePointDeduction = false
        this.form.useCryptocurrencyDeduction = false
        this.form.useVipPrice = false
        this.form.useCouponDeduction = false
        this.form.couponId = null
        this.confirm()
        return
      }
      this.PrePoints = index
      this.promotionType = this.paySetting.promotions[index]?.type
      console.debug('promotionType=', this.promotionType)
      if (this.promotionType == 30) {
        // 红包抵扣
        this.form.useRedPacketDeduction = true
        this.form.usePointDeduction = false
        this.form.useCryptocurrencyDeduction = false
        this.form.useVipPrice = false
        this.form.useCouponDeduction = false
        this.form.couponId = null
        this.needLoginPopup = !this.newCustomer.login
      } else if (this.promotionType == 7) {
        // 优惠券
        this.form.useRedPacketDeduction = false
        this.form.usePointDeduction = false
        this.form.useCryptocurrencyDeduction = false
        this.form.useVipPrice = false
        this.form.useCouponDeduction = true
        this.needLoginPopup = !this.newCustomer.login
        this.showCouponPopup = this.needLoginPopup ? false : true
      } else if (this.promotionType == 8) {
        // 积分抵扣
        this.form.useRedPacketDeduction = false
        this.form.usePointDeduction = true
        this.form.useCryptocurrencyDeduction = false
        this.form.useVipPrice = false
        this.form.useCouponDeduction = false
        this.form.couponId = null
        this.needLoginPopup = !this.newCustomer.login
      } else if (this.promotionType == 9) {
        // 会员价
        this.form.useRedPacketDeduction = false
        this.form.usePointDeduction = false
        this.form.useCryptocurrencyDeduction = false
        this.form.useVipPrice = true
        this.form.useCouponDeduction = false
        this.form.couponId = null
        this.needLoginPopup = !this.newCustomer.login || !this.userInfo || !this.userInfo.isVip
      } else if (this.promotionType == 20) {
        // 收益豆抵扣
        this.form.useRedPacketDeduction = false
        this.form.usePointDeduction = false
        this.form.useCryptocurrencyDeduction = true
        this.form.useVipPrice = false
        this.form.useCouponDeduction = false
        this.form.couponId = null
        this.needLoginPopup = !this.newCustomer.login
      }
      this.confirm()
    },
    selectCoupon(coupon) {
      this.form.couponId = coupon.id
      this.showCouponPopup = false
      this.confirm()
    },
    onPointList(index) {
      const type = this.paySetting.promotions[index]?.type
      if (type == 7) {
        // 优惠券
        uni.navigateTo({
          url: '/other/my-coupon/my-coupon'
        })
      } else if (type == 8) {
        // 积分抵扣
        uni.navigateTo({
          url: '/other/integral/integral'
        })
      } else if (type == 20) {
        // 收益豆抵扣
        uni.navigateTo({
          url: '/alliance/income'
        })
      } else if (type == 30) {
        // 红包抵扣
        uni.navigateTo({
          url: '/other/my-coupon/my-red-packet'
        })
      }
    },
    toLogin() {
      this.$utils.goToLogin('/dine/pay-view/pay-view?shopId=' + this.form.shopId)
    },
    wxLogin(e) {
      const self = this
      uni.login({
        provider: 'weixin',
        success: (res) => {
          self.loginByPhone(res.code, e.detail.code)
        },
        fail: () => {
          self.$u.toast('微信授权登录失败')
        }
      })
    },
    loginByPhone(loginCode = '', phoneCode = '') {
      const self = this
      if (self.$u.test.isEmpty(loginCode)) {
        self.$u.toast('微信授权登录失败')
        return
      }
      if (self.$u.test.isEmpty(phoneCode)) {
        self.$u.toast('请先授权获取手机号')
        return
      }
      self.$u.api
        .setWechatLogin({
          loginCode: loginCode,
          phoneCode: phoneCode,
          state: loginCode,
          inviteCode: uni.getStorageSync('saleMemberNo') || ''
        })
        .then((res) => {
          if (Number(res.code) !== 0) {
            self.$u.toast(res.msg)
            return
          }
          uni.setStorageSync('tokenInfo', res.data)
          self.$u.api.getUserInfo().then((res) => {
            self.userInfo = res.data
            uni.setStorageSync('userInfo', res.data)
            self.refreshData()
          })
        })
    },
    newCustomerPay(price, originPrice) {
      if (this.disable) {
        return
      }
      this.disable = true
      this.$u
        .post('/app-api/trade/order/offline-scan/submit-new-customer', {
          shopId: this.form.shopId,
          originPrice,
          price
        })
        .then((res) => {
          if (res.code === 0) {
            this.payOrderId = res.data.tradeNo
            this.payPrice = res.data.price
            this.discountPrice = res.data.discountPrice
            this.$refs.payPopupRef.open(this.payOrderId, this.openid, this.payPrice === 0)
            this.disable = false
          } else {
            this.$u.toast(res.msg)
            this.disable = false
          }
        })
        .catch(() => {
          this.disable = false
        })
    },
    toSvip() {
      if (!this.userInfo) {
        this.toLogin()
        return
      }
      uni.setStorageSync('backUrl', '/dine/pay-view/pay-view?shopId=' + this.form.shopId)
      uni.navigateTo({
        url: '/users/svip'
      })
    },
    toShop() {
      if (this.shopInfo.categoryCode === 'food') {
        uni.navigateTo({
          url: '/dine/diancan/diancanv2?shopId=' + this.form.shopId
        })
        return
      }
      uni.navigateTo({
        url: '/other/merchant-center/merchant-center?id=' + this.form.shopId
      })
    },
    giveUp() {
      this.needLoginPopup = false
      this.onPreAll(-1)
    },
    submit() {
      if (this.form.useCouponDeduction) {
        const couponId = Number(this.form.couponId)
        this.showCouponPopup = isNaN(couponId) || couponId <= 0
        if (this.showCouponPopup) {
          this.$u.toast('请选择要用来抵扣的优惠券')
          return
        }
      }
      if (this.disable) {
        return
      }
      this.disable = true
      this.$u
        .post('/app-api/trade/order/offline-scan/submit', this.form)
        .then((res) => {
          if (res.code === 0) {
            this.payOrderId = res.data.tradeNo
            this.$refs.payPopupRef.open(this.payOrderId, this.openid, res.data.price === 0)
            this.promotionModel = false
            this.disable = false
          } else {
            this.$u.toast(res.msg)
            this.disable = false
          }
        })
        .catch(() => {
          this.disable = false
        })
    },
    closePay() {
      this.$u.post('/app-api/pay/order/close?tradeNo=' + this.payOrderId)
      if (this.promotionModel) {
        this.promotionModel = false
      }
      if (this.newCustomer.enabled) {
        this.checkCustomer()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import url('@/style/btn.css');

.disable {
  background: #efefef;
  color: #999;
  opacity: 0.9;
}

.card {
  margin: 20rpx;
  background-color: #fff;
  padding: 20rpx;
  border-radius: 10rpx;
  position: relative;
}

.store-name {
  margin-left: 20rpx;
  font-weight: 600;
  font-size: 34rpx;
  color: #333333;
  flex-flow: column;
}

.rule_btn ::v-deep .u-btn {
  background-color: transparent !important;
  border-color: transparent !important;
  padding: 0 !important;
  margin-top: -10rpx !important;
  margin-left: 20rpx !important;
}

.login_btn {
  width: calc(100% - 60rpx);
  height: 80rpx;
  line-height: 80rpx;
  background-color: rgba(0, 154, 116, 0.2);
  color: #009a74;
  border-radius: 35rpx;
  z-index: 999;
  cursor: pointer;
  margin: 20rpx 30rpx;
  text-align: center;
}

.rule_box {
  padding: 45rpx 30rpx 35rpx 30rpx;

  .tl {
    font-weight: 600;
    font-size: 34rpx;
    margin-bottom: 45rpx;
    text-align: center;
  }

  .content {
    font-size: 30rpx;
    line-height: 45rpx;
  }

  .bt {
    width: 240rpx;
    height: 72rpx;
    background: #10a28f;
    border-radius: 36rpx;
    margin: auto;
    font-size: 30rpx;
    color: #ffffff;
    line-height: 72rpx;
    margin-top: 35rpx;
    text-align: center;
  }
}

.pay-input {
  margin-top: 0;
  padding: 30rpx;
  font-size: 36rpx;
}

.category {
  margin-top: 20rpx;
  font-size: 28rpx;
  font-weight: 400;
  // background-color: #efefef;
  // border-radius: 35rpx;
  // padding: 10rpx 30rpx;
}

.infoView {
  display: flex;
  flex-direction: column;
  background: #ffffff;
  border-radius: 12rpx;
  padding: 100rpx 20rpx 20rpx;

  .totalView {
    flex-direction: row;
    align-items: center;
    padding: 20rpx;

    .totalTitle {
      font-size: 30rpx;
      font-weight: 400;
      color: #333333;
    }

    .totalPrice {
      font-size: 30rpx;
      font-weight: 400;
      color: #999999;
    }
  }

  .open-vip {
    padding: 20rpx;

    .vip-tl {
      padding-bottom: 10rpx;

      .bt {
        width: 150rpx;
        height: 50rpx;
        background: linear-gradient(90deg, #f5cd71, #f5e39d);
        border-radius: 25rpx;
        font-size: 24rpx;
        color: #995406;
      }

      .des {
        margin-left: 10rpx;
        font-size: 28rpx;
        color: #333333;

        .col {
          color: #fa453c;
        }

        .bold {
          font-size: 36rpx;
          margin: 0 2rpx;
        }
      }
    }

    .vip-qy {
      font-weight: 600;
      font-size: 28rpx;
      color: #333333;
      margin: 10rpx 0;
    }

    .description {
      font-size: 24rpx;
      color: #999999;
    }
  }

  .pay-method {
    margin-top: 40rpx;
  }

  .mr-20 {
    margin-right: 20rpx;
  }
}

.fixed-wapper {
  .other {
    width: 100%;
    background: #333333;
    border-radius: 40rpx;
    margin-bottom: 20rpx;

    .count {
      font-weight: 600;
      font-size: 36rpx;
      color: #ffffff;
      padding: 0 50rpx;
    }

    .submit-btn {
      width: 200rpx;
      right: 0;
    }
  }
}

.can-select,
.cant-select {
  width: 36rpx;
  height: 36rpx;
  border-radius: 50%;
}

.cant-select {
  background-color: #eee;
}

.close-wapper {
  text-align: center;
  padding: 0;

  .title {
    padding: 30rpx 20rpx;
    font-size: 32rpx;
    font-weight: 600;
  }

  .des {
    padding: 0 40rpx;
  }

  .bt-group {
    margin-top: 30rpx;
    border-top: 1rpx solid #efefef;
    height: 100rpx;

    .bt {
      flex: 1;
      background-color: #009a74;
      color: #fff;
      height: 100rpx;
      line-height: 100rpx;
      text-align: center;
      border-radius: 0;
    }

    .bt-1 {
      // border-left: 1rpx solid #efefef;
      background-color: #e5e5e5;
      color: #333;
    }
  }
}

.toshop {
  background-color: #009a74;
  position: absolute;
  right: 20rpx;
  top: 75rpx;
  padding: 10rpx 30rpx;
  color: #ffffff;
  border-radius: 35rpx;
  z-index: 999;
  cursor: pointer;
}

.guide-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #009a74;
  color: #ffffff;
  border-radius: 35rpx;
  z-index: 999;
  cursor: pointer;
  margin: 20rpx 30rpx;
  text-align: center;
}

.origin-btn {
  background-color: rgba(0, 154, 116, 0.2);
  color: #009a74;
}

.coupon-popup {
  padding: 20rpx;

  .popup-header {
    text-align: center;
    padding: 20rpx 0;
    font-size: 32rpx;
    font-weight: bold;
    position: relative;
  }

  .coupon-item {
    display: flex;
    align-items: center;
    padding: 20rpx;
    border-top: 1rpx solid #eee;

    .coupon-info {
      flex: 1;
      display: flex;
      flex-direction: column;

      .coupon-name {
        font-size: 28rpx;
        font-weight: bold;
      }

      .coupon-desc {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}
</style>
